package cn.itcast.jx.service.impl;

import java.io.Serializable;
import java.util.List;

import cn.itcast.jx.dao.BaseDao;
import cn.itcast.jx.domain.Contract;
import cn.itcast.jx.domain.ExtCproduct;
import cn.itcast.jx.service.ExtCproductService;
import cn.itcast.jx.util.Page;
import cn.itcast.jx.util.UtilFuns;

public class ExtCproductServiceImpl implements ExtCproductService{

	private BaseDao baseDao;

	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}

	@Override
	public Page<ExtCproduct> findPage(String hql, Page<ExtCproduct> page,
			Class<ExtCproduct> entityClass, Object[] params) {
		return baseDao.findPage(hql, page, entityClass, params);
	}

	@Override
	public ExtCproduct get(Class<ExtCproduct> entityClass, Serializable id) {
		// TODO Auto-generated method stub
		return baseDao.get(entityClass, id);
	}

	@Override
	public void saveOrUpdate(ExtCproduct entity) {
		if(UtilFuns.isEmpty(entity.getId())) {
			if(UtilFuns.isNotEmpty(entity.getPrice()) && UtilFuns.isNotEmpty(entity.getCnumber())) {
				entity.setAmount(entity.getPrice() * entity.getCnumber());
			}
			//Contract contract = entity.getContractProduct().getContract();错误的
			Contract contract = baseDao.get(Contract.class, entity.getContractProduct().getContract().getId());
			
			contract.setTotalAmount(contract.getTotalAmount() + entity.getAmount());
			baseDao.saveOrUpdate(entity);
			baseDao.saveOrUpdate(contract);
		}else {
			//修改
			//hibernate 中一级缓存直接拿数据
			ExtCproduct extCproduct = baseDao.get(ExtCproduct.class, entity.getId());
			
			Double amount = 0d;
			
			if(UtilFuns.isNotEmpty(entity.getPrice()) && UtilFuns.isNotEmpty(entity.getCnumber())) {
				amount = entity.getPrice() * entity.getCnumber();
			}
			
			Contract contract = extCproduct.getContractProduct().getContract();
			contract.setTotalAmount(contract.getTotalAmount() - extCproduct.getAmount() + amount);
			
			extCproduct.setAmount(amount);
			
			//更新
			baseDao.saveOrUpdate(extCproduct);
			baseDao.saveOrUpdate(contract);
		}
	}

	@Override
	public void delete(Class<ExtCproduct> entityClass, String[] ids) {
		String id = ids[0];
		
		ExtCproduct extCproduct = baseDao.get(ExtCproduct.class, id);
		Contract contract = extCproduct.getContractProduct().getContract();
		contract.setTotalAmount(contract.getTotalAmount() - extCproduct.getAmount());
		baseDao.saveOrUpdate(contract);
		baseDao.deleteById(ExtCproduct.class, id);
		
	}

	@Override
	public List<ExtCproduct> find(String hql, Class<ExtCproduct> entityClass,
			Object[] params) {
		// TODO Auto-generated method stub
		return baseDao.find(hql, entityClass, params);
	}
	
}
